package org.qiyu.liv.living.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.idea.qiyu.live.framework.redis.starter.key.LivingProviderCacheKeyBuilder;
import org.qiyu.liv.living.provider.dao.mapper.LivingRoomMapper;
import org.qiyu.liv.living.provider.dao.mapper.LivingRoomRecordMapper;
import org.qiyu.liv.living.provider.dao.po.LivingRoomPO;
import org.qiyu.liv.living.provider.dao.po.LivingRoomRecordPO;
import org.qiyu.liv.living.provider.service.ILivingRoomService;
import org.qiyu.live.common.interfaces.dto.PageWrapper;
import org.qiyu.live.common.interfaces.enums.CommonStatusEum;
import org.qiyu.live.common.interfaces.utils.ConvertBeanUtils;
import org.qiyu.live.living.interfaces.dto.LivingRoomReqDTO;
import org.qiyu.live.living.interfaces.dto.LivingRoomRespDTO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: //todo
 * @Author: 张广焱
 * @Date: 2023-12-13 21:12
 */
@Service
public class ILivingRoomServiceImpl implements ILivingRoomService {
    @Resource
    private LivingRoomMapper livingRoomMapper;
    @Resource
    private LivingRoomRecordMapper livingRoomRecordMapper;
    @Resource
    private LivingProviderCacheKeyBuilder cacheKeyBuilder;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Integer startLivingRoom(LivingRoomReqDTO livingRoomRecordPO) {
        LivingRoomPO livingRoomPO = ConvertBeanUtils.convert(livingRoomRecordPO, LivingRoomPO.class);
        livingRoomPO.setStatus(CommonStatusEum.VALID_STATUS.getCode());
        livingRoomPO.setStartTime(new Date());
        livingRoomMapper.insert(livingRoomPO);
        String cacheKey = cacheKeyBuilder.buildLivingRoomObj(livingRoomPO.getId());
        //防止之前有空值缓存,这里做移除
        redisTemplate.delete(cacheKey);
        return livingRoomPO.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean closeLiving(LivingRoomReqDTO livingRoomReqDTO) {
        LivingRoomPO livingRoomPO = livingRoomMapper.selectById(livingRoomReqDTO.getRoomId());
        if (livingRoomPO == null) {
            return false;
        }
        if (!(livingRoomPO.getAnchorId().equals(livingRoomReqDTO.getAnchorId()))) {
            return false;
        }
        LivingRoomRecordPO convert = ConvertBeanUtils.convert(livingRoomPO, LivingRoomRecordPO.class);
        convert.setStartTime(new Date());
        livingRoomRecordMapper.insert(convert);
        livingRoomMapper.deleteById(livingRoomReqDTO.getId());
        //移除掉直播间的cache
        String cacheKey = cacheKeyBuilder.buildLivingRoomObj(livingRoomReqDTO.getRoomId());
        redisTemplate.delete(cacheKey);
        return true;
    }

    @Override
    public LivingRoomRespDTO queryByRoomId(Integer roomId) {
        String cacheKey = cacheKeyBuilder.buildLivingRoomObj(roomId);
        LivingRoomRespDTO queryResult = (LivingRoomRespDTO) redisTemplate.opsForValue().get(cacheKey);
        if (queryResult != null) {
            //空值缓存
            if (queryResult.getId() == null) {
                return null;
            }
            return queryResult;
        }
        LambdaQueryWrapper<LivingRoomPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LivingRoomPO::getId, roomId)
                .eq(LivingRoomPO::getStatus, CommonStatusEum.VALID_STATUS.getCode()).last("limit 1");
        queryResult = ConvertBeanUtils.convert(livingRoomMapper.selectById(queryWrapper), LivingRoomRespDTO.class);
        if (queryResult == null) {
            //防止缓存击穿
            redisTemplate.opsForValue().set(cacheKey, new LivingRoomRespDTO(), 1, TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(cacheKey, queryResult, 30, TimeUnit.MINUTES);
        return queryResult;

    }

    @Override
    public PageWrapper<LivingRoomRespDTO> list(LivingRoomReqDTO livingRoomReqDTO) {
        //获取key
        String cachekey = cacheKeyBuilder.buildLivingRoomList(livingRoomReqDTO.getType());
        int page = livingRoomReqDTO.getPage();
        int pageSize = livingRoomReqDTO.getPageSize();
        //获取总数
        Long size = redisTemplate.opsForList().size(cachekey);
        //获取分页数据
        List<Object> resultList = redisTemplate.opsForList().range(cachekey, (page - 1) * pageSize, page * pageSize - 1);
        PageWrapper<LivingRoomRespDTO> pageWrapper = new PageWrapper<>();
        if (CollectionUtils.isEmpty(resultList)) {
            //Collections.emptyList() 返回一个空的数组
            pageWrapper.setList(Collections.emptyList());
            pageWrapper.setHasNext(false);
            return pageWrapper;
        } else {
            List<LivingRoomRespDTO> convert = ConvertBeanUtils.convertList(resultList, LivingRoomRespDTO.class);
            pageWrapper.setList(convert);
            pageWrapper.setHasNext(page * pageSize < size);
            return pageWrapper;
        }

    }

    @Override
    public List<LivingRoomRespDTO> listAllLivingRoomFromDB(Integer type) {
        LambdaQueryWrapper<LivingRoomPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LivingRoomPO::getStatus, CommonStatusEum.VALID_STATUS.getCode())
                .eq(LivingRoomPO::getType, type)
                //按照事件倒叙展示
                .orderByDesc(LivingRoomPO::getStartTime)
                .last("limit 1000");
        return ConvertBeanUtils.convertList(livingRoomMapper.selectList(queryWrapper), LivingRoomRespDTO.class);
    }
//        LambdaQueryWrapper<LivingRoomPO> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(LivingRoomPO::getType,livingRoomReqDTO.getType())
//                .eq(LivingRoomPO::getStatus,CommonStatusEum.VALID_STATUS.getCode());
//        Page<LivingRoomPO> livingRoomPOPage = livingRoomMapper.selectPage(new Page<>((long) livingRoomReqDTO.getPage(), (long) livingRoomReqDTO.getPageSize()), queryWrapper);
//        PageWrapper<LivingRoomRespDTO> objectPageWrapper = new PageWrapper<>();
//        objectPageWrapper.setList( ConvertBeanUtils.convertList(livingRoomPOPage.getRecords(),LivingRoomRespDTO.class));
//        objectPageWrapper.setHasNext(livingRoomReqDTO.getPage()*livingRoomReqDTO.getPageSize()<livingRoomPOPage.getTotal());
//
//        return objectPageWrapper;
//    }
}
